package com.example.demo.interceptor;

import com.example.demo.annotation.Token;
import com.example.demo.config.State;
import com.example.demo.exception.BusinessException;
import com.example.demo.session.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class Authlnterceptor implements HandlerInterceptor {
    @Autowired
    private HttpSession httpSession;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null) {
            token = token.replaceAll("Bearer", "").replaceAll("\"", "").replaceAll(" ", "");
        }
        if (!(handler instanceof HandlerMethod))
            return true;
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class<?> class1 = handlerMethod.getBeanType();
        if (class1.isAnnotationPresent(Token.class)) {
            Token token1 = class1.getAnnotation(Token.class);
            if (token1.required()) {
                Object obj = httpSession.get(token);
                if (obj == null) {
                   throw new BusinessException(State.NOTLOGIN,"用户未登录");
                }
            }
        }
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(Token.class)) {
            Token token1 = method.getAnnotation(Token.class);
            if (token1.required()) {
                Object obj = httpSession.get(token);
                if (obj!=null){
                    return true;
                }else {
                    throw new BusinessException(State.NOTLOGIN,"用户未登录");
                }
            }
            return true;
        }
        return true;
    }
}
